import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:${USER}
 * Date:${YEAR}-${MONTH}-${DAY}
 * ${TIME}
 */
public class Main {
    public int[] findOrder(int n, int[][] p) {
        int[] in=new int[n];
        Map<Integer, List<Integer>> ed=new LinkedHashMap<>();
        int[] result=new int[n];
        for (int i = 0; i < p.length; i++) {
            int a=p[i][0];int b=p[i][1];
            if(!ed.containsKey(b)){
                ed.put(b,new ArrayList<>());
            }
            ed.get(b).add(a);
            in[a]++;
        }
        Queue<Integer> q=new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if(in[i]==0)q.add(i);
        }
        int k=0;
        while (!q.isEmpty()){
            int t=q.poll();
            result[k++]=t;
            for (int a:ed.getOrDefault(t,new ArrayList<>())) {
                in[a]--;
                if(in[a]==0)q.add(a);
            }
        }
        for (int x:in) {
            if(x!=0) {
                return new int[0];
            }
        }
        return result;
    }
}